package com.kaichaohulian.baocms.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.base.BaseActivity;
import com.kaichaohulian.baocms.ecdemo.common.utils.ToastUtil;
import com.kaichaohulian.baocms.entity.CommonEntity;
import com.kaichaohulian.baocms.http.HttpResult;
import com.kaichaohulian.baocms.http.HttpUtil;
import com.kaichaohulian.baocms.http.Url;
import com.kaichaohulian.baocms.retrofit.RetrofitClient;
import com.kaichaohulian.baocms.rxjava.BaseObjObserver;
import com.kaichaohulian.baocms.rxjava.RxUtils;
import com.kaichaohulian.baocms.utils.DBLog;
import com.kaichaohulian.baocms.view.ShowDialog;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.kaichaohulian.baocms.activity.RegisterActivity.isMobile;


public class changPwdActivity extends BaseActivity {


    @BindView(R.id.edt_original_password)
    EditText edtOriginalPassword;
    @BindView(R.id.edt_new_password)
    EditText edtNewPassword;
    @BindView(R.id.edt_againnew_password)
    EditText edtAgainnewPassword;
    @BindView(R.id.btn_changePwd)
    Button btnChangePwd;
    private TextWatcher textWatcher;
    @BindView(R.id.edit_phone)
    EditText edit_phone;
    @BindView(R.id.et_register_code)
    EditText et_register_code;
    @BindView(R.id.tv_register_code)
    TextView tv_register_code;

    @Override
    public void setContent() {
        setContentView(R.layout.activity_chang_pwd);
        ButterKnife.bind(this);
        setCenterTitle("密码修改");
    }

    @Override
    public void initData() {
    }

    @Override
    public void initView() {
        btnChangePwd.setClickable(false);
//        btnChangePwd.setBackgroundResource(R.mipmap.deeporange_bar_normal);
        if (textWatcher == null) {
            textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (edtAgainnewPassword.getText().length() > 6 && edtNewPassword.getText().length() > 6 && edtOriginalPassword.getText().length() > 6) {
//                        btnChangePwd.setBackgroundResource(R.mipmap.deeporange_bar_part);
                        btnChangePwd.setClickable(true);
                    } else {
//                        btnChangePwd.setBackgroundResource(R.mipmap.deeporange_bar_normal);
                        btnChangePwd.setClickable(true);
                    }
                }
            };
        }
        edtOriginalPassword.addTextChangedListener(textWatcher);
        edtNewPassword.addTextChangedListener(textWatcher);
        edtAgainnewPassword.addTextChangedListener(textWatcher);
    }

    @Override
    public void initEvent() {

    }

    @OnClick({R.id.btn_changePwd, R.id.tv_register_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_changePwd:

                if (TextUtils.isEmpty(edtOriginalPassword.getText().toString().trim())) {
                    Toast.makeText(this, "原密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(edtNewPassword.getText().toString().trim())) {
                    Toast.makeText(this, "新密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (!edtOriginalPassword.getText().toString().trim().equals(edtNewPassword.getText().toString().trim())) {
                    Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(et_register_code.getText().toString().trim())) {
                    Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                }   else {

                    if (map == null) {
                        map = new HashMap<>();
                    } else {
                        map.clear();
                    }

                    map.put("newPassword", edtOriginalPassword.getText().toString().trim());
                    map.put("reNewPassword", edtNewPassword.getText().toString().trim());
                    map.put("phoneNumber", MyApplication.getInstance().UserInfo.getPhoneNumber());
                    map.put("code",et_register_code.getText().toString().trim());
                    map.put("userId",MyApplication.getInstance().UserInfo.getUserId()+"");
                    RetrofitClient.getInstance().createApi().ChangePassWord(map)
                            .compose(RxUtils.<HttpResult<CommonEntity>>io_main())
                            .subscribe(new BaseObjObserver<CommonEntity>(getActivity()) {
                                @Override
                                protected void onHandleSuccess(CommonEntity commonEntity) {
                                    Toast.makeText(changPwdActivity.this, "修改密码成功", Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            });

                }
                break;
            case R.id.tv_register_code:

                if (TextUtils.isEmpty(edit_phone.getText().toString().trim())) {
                    Toast.makeText(changPwdActivity.this, "手机号码不能为空", Toast.LENGTH_LONG).show();
                }else if (!isMobile(edit_phone.getText().toString().trim())){
                    Toast.makeText(changPwdActivity.this, "请输入正确的手机号", Toast.LENGTH_LONG).show();
                }else {
                    getCode();
                }

                break;
        }






    }
    private Timer mTimer;
    private int mTime = 60;
    private String phone;
    private void getCode() {
        if (mTimer == null) {
            mTimer = new Timer();
            mTime = 60;
            tv_register_code.setText(mTime + "s后重新获取");
            tv_register_code.setEnabled(false);
        } else {
            return;
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        mTime--;
                        tv_register_code.setText(mTime + "s后重新获取");
                        if (mTime == 0) {
                            mTimer.cancel();
                            mTimer = null;
                            tv_register_code.setText("重新验证");
                            tv_register_code.setEnabled(true);
                        }
                    }
                });
            }
        }, 0, 1000);
        ShowDialog.showDialog(getActivity(), "发送中...", false, null);
        phone = edit_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showMessage("请输入手机号");
            return;
        }
        RequestParams params = new RequestParams();
        params.put("phoneNumber", phone);
        HttpUtil.post(Url.sendMessage, params, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.d("33333333333333333", Url.sendMessage);

                    DBLog.e("验证码", response.toString());
                    if (response.getInt("code") == 0) {
//                        Bundle Bundle = new Bundle();
//                        Bundle.putString("phoneNumber", phone);
//                        ActivityUtil.next(getActivity(), RegisterActivity2.class, Bundle);
                    }
                    showToastMsg(response.getString("errorDescription"));
                } catch (Exception e) {
                    showToastMsg("发送失败");
                    Log.d("33333333333333333",Url.sendMessage);
                    e.printStackTrace();

                } finally {
                    Log.d("33333333333333333",Url.sendMessage);
                    ShowDialog.dissmiss();
                }
            }

            @Override
            public void onCancel() {
                Log.d("33333333333333333",Url.sendMessage);
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToastMsg("请求服务器失败");
                DBLog.e("tag", statusCode + ":" + responseString);
                ShowDialog.dissmiss();
            }
        });
    }

}
